import random
import psutil


def get_listening_ports():
    """
    获取监听的端口
    """
    ports = []
    for conn in psutil.net_connections(kind='tcp'):
        if conn.status == psutil.CONN_LISTEN:
            ports.append(conn.laddr.port)
    return ports


def use_open_port():
    """
    随机生成port，判断与原来的是否冲突，不冲突则使用
    """
    for _ in range(3000):
        a = random.randint(7, 9)
        b = random.randint(0, 9)
        c = random.randint(0, 9)
        d = random.randint(0, 9)
        port = f"{a}{b}{c}{d}"
        if int(port) not in get_listening_ports():
            return int(port)
    # 存在则返回默认值
    return None
